<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/28
 * Time: 11:23
 */

namespace App\Process;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\Timer;
use EasySwoole\HttpClient\HttpClient;

class KogBet extends AbstractProcess
{
    public function run($arg)
    {
        // TODO: Implement run() method.
        go(function ()use($arg){
            Timer::getInstance()->loop(15000,function (){
                $match_ids = MysqlPool::invoke(function (MysqlObject $db) {
                    return $db->whereIn('status', [0, 1])->getColumn('siam_kogmatchs', 'match_id');
                });

                foreach ( $match_ids as $match_id ){
                    list($s1, $s2) = explode(' ', microtime());
                    $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                    $url = UrlEnums::FJURL.UrlEnums::KOG_BET_PATH."?match_id={$match_id}&version=2";
                    $client = new HttpClient($url);
                    $option = [
                        'path'      => UrlEnums::KOG_BET_PATH,
                        'api_time'  => $microtime
                    ];
                    $header = Auth::getInstance()->header($option);
                    $client->setHeaders($header,true,false);
                    $response = $client->get();
                    $content = $response->getBody();
                    $data = json_decode($content,true);
                    if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                        $data = json_decode($content,true);
                        MysqlPool::invoke(function (MysqlObject $db)use($data){
                            foreach ( $data['data'] as $k=>$v ){
                                $v['options'] = json_encode($v['options']);
                                $res = $db->where('bet_id',$v['bet_id'])->getOne('siam_kogbet');
                                if( !$res ){
                                    $raw = $db->insert('siam_kogbet',$v);
                                }else{
                                    $raw = $db->where('bet_id',$v['bet_id'])->update('siam_kogbet',[
                                        'options' => $v['options'],
                                        'status'  => $v['status']
                                    ]);
                                }
                            }
                        });

                    }
                }
            });
        });
    }
}